package org.springblade.common.security.extractor;

import org.springblade.core.launch.constant.TokenConstant;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

public class CsjBearerTokenExtractor extends BearerTokenExtractor {
	@Override
	protected String extractHeaderToken(HttpServletRequest request) {
		Enumeration headers = request.getHeaders(TokenConstant.HEADER);

		String value;
		do {
			if (!headers.hasMoreElements()) {
				return null;
			}

			value = (String)headers.nextElement();
		} while(!value.toLowerCase().startsWith("Bearer".toLowerCase()));

		String authHeaderValue = value.substring("Bearer".length()).trim();
		request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, value.substring(0, "Bearer".length()).trim());
		int commaIndex = authHeaderValue.indexOf(44);
		if (commaIndex > 0) {
			authHeaderValue = authHeaderValue.substring(0, commaIndex);
		}

		return authHeaderValue;
	}
}
